package com.sky.service.impl;

import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    private final ShoppingCartMapper cartMapper;
    private final DishMapper dishMapper;
    private final SetmealMapper setmealMapper;

    @Autowired
    public ShoppingCartServiceImpl(ShoppingCartMapper cartMapper, DishMapper dishMapper, SetmealMapper setmealMapper) {
        this.cartMapper = cartMapper;
        this.dishMapper = dishMapper;
        this.setmealMapper = setmealMapper;
    }


    /**
     * 用户购物车添加商品接口
     *
     * @param cartDTO 购车车dto
     */
    @Override
    @Transactional
    public void addShoppingCart(ShoppingCartDTO cartDTO) {
        //判断当前加入购物车中的商品是否存在
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(cartDTO, shoppingCart);
        shoppingCart.setUserId(ThreadLocalUtil.get());
        // 判断商品是否存在于购物车
        int count = cartMapper.countByConditions(shoppingCart);
        //如果存在了，只需要将数量加一
        if (count > 0) {
            // 如果存在，更新数量
            cartMapper.updateNumberByConditions(shoppingCart);
        } else {
            //如果不存在，需要插入一条数据
            //判断是否为菜品 还是套餐
            Long dishId = cartDTO.getDishId();
            Long setmealId = cartDTO.getSetmealId();
            if (dishId != null) {
                //本次添加到购物车的是菜品
                Dish dish = dishMapper.getById(dishId);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            } else {
                //本次添加的是套餐
                Setmeal setmeal = setmealMapper.findById(setmealId);
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            cartMapper.insert(shoppingCart);
        }
    }

    /**
     * 获取当前登录用户的购物车
     *
     * @return 购物车所有商品
     */
    @Override
    public List<ShoppingCart> list() {
        //直接调用list方法 查询当前用户下的所有购物车中的商品
        return cartMapper.list(ShoppingCart.builder().userId(ThreadLocalUtil.get()).build());
    }

    /**
     * 删除购物车中一个商品
     *
     * @param dto dto
     */
    @Override
    public void deleteOneItem(ShoppingCartDTO dto) {
        Long userId = ThreadLocalUtil.get();
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(userId);
        BeanUtils.copyProperties(dto, cart);
        if (cart.getDishId() != null || cart.getSetmealId() != null) {
            // 更新数量（如果数量大于等于 2）
            int updatedRows = cartMapper.updateNumberIfGreaterThanTwo(cart);
            log.info("数量：{}", updatedRows);
            if (updatedRows == 0) {
                // 如果没有更新成功，则直接删除
                cartMapper.delete(cart);
            }
        } else {
            cartMapper.delete(cart);
        }
    }

    @Override
    public void clearCart() {
        Long userId = ThreadLocalUtil.get();
        cartMapper.deleteAllByUserId(userId);
    }

}
